<template>
  <el-button @click="handelClick" :disabled="timeFlag > 0">{{
    btnMsg
  }}</el-button>
</template>
<script>
export default {
  data() {
    return {
      btnInfo: {
        regain: '重新获取',
        getCodeInfo: '获取验证码',
        totalTime: 5
      },
      timeFlag: 0 //0表示还没有点击按钮
    }
  },
  props: {
    getCode: {
      type: Function,
      default: null
    }
  },
  methods: {
    async handelClick() {
      const isHaveGetCode = this.getCode && (await this.getCode())
      if (!isHaveGetCode) return
      // 如果获取验证码函数传过来了就继续
      this.timeFlag = this.btnInfo.totalTime
      const timer = setInterval(() => {
        this.timeFlag--
        if (this.timeFlag === 0) clearInterval(timer)
      }, 1000)
    }
  },
  computed: {
    btnMsg() {
      return this.timeFlag
        ? `${this.timeFlag}` + 's后' + `${this.btnInfo.regain}`
        : '点击' + `${this.btnInfo.getCodeInfo}`
    }
  }
}
</script>
<style lang="scss" scoped></style>
